/**
 * 通用验证规则库
 * 提供统一的表单验证规则，减少重复代码
 */

import type { FormRules } from 'element-plus'

// 基础验证规则
export const baseValidationRules = {
  // 必填验证
  required: (message: string) => [
    { required: true, message, trigger: 'blur' }
  ],

  // 长度验证
  length: (min: number, max: number, message?: string) => [
    { min, max, message: message || `长度在 ${min} 到 ${max} 个字符`, trigger: 'blur' }
  ],

  // 邮箱验证
  email: (message?: string) => [
    { type: 'email' as const, message: message || '请输入正确的邮箱格式', trigger: 'blur' }
  ],

  // 手机号验证
  phone: (message?: string) => [
    { pattern: /^1[3-9]\d{9}$/, message: message || '请输入正确的手机号格式', trigger: 'blur' }
  ],

  // 数字验证
  number: (message?: string) => [
    { type: 'number' as const, message: message || '请输入数字', trigger: 'blur' }
  ],

  // 整数验证
  integer: (message?: string) => [
    { pattern: /^\d+$/, message: message || '请输入整数', trigger: 'blur' }
  ],

  // 正整数验证
  positiveInteger: (message?: string) => [
    { pattern: /^[1-9]\d*$/, message: message || '请输入正整数', trigger: 'blur' }
  ],

  // 密码验证
  password: (minLength = 6, maxLength = 20) => [
    { min: minLength, max: maxLength, message: `密码长度在 ${minLength} 到 ${maxLength} 个字符`, trigger: 'blur' },
    { pattern: /^(?=.*[a-zA-Z])(?=.*\d)/, message: '密码必须包含字母和数字', trigger: 'blur' }
  ],

  // 用户名验证
  username: (minLength = 2, maxLength = 20) => [
    { min: minLength, max: maxLength, message: `用户名长度在 ${minLength} 到 ${maxLength} 个字符`, trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],

  // URL验证
  url: (message?: string) => [
    { pattern: /^https?:\/\/.+/, message: message || '请输入正确的URL格式', trigger: 'blur' }
  ],

  // 中文验证
  chinese: (message?: string) => [
    { pattern: /^[\u4e00-\u9fa5]+$/, message: message || '请输入中文', trigger: 'blur' }
  ],

  // 英文验证
  english: (message?: string) => [
    { pattern: /^[a-zA-Z]+$/, message: message || '请输入英文', trigger: 'blur' }
  ],

  // 数字和字母验证
  alphanumeric: (message?: string) => [
    { pattern: /^[a-zA-Z0-9]+$/, message: message || '只能包含字母和数字', trigger: 'blur' }
  ],

  // 自定义正则验证
  pattern: (pattern: RegExp, message: string) => [
    { pattern, message, trigger: 'blur' }
  ]
}

// 业务验证规则
export const businessValidationRules = {
  // 用户相关验证
  user: {
    form: (): FormRules => ({
      userName: [
        ...baseValidationRules.required('请输入用户名'),
        ...baseValidationRules.username(2, 20)
      ],
      nickName: [
        ...baseValidationRules.required('请输入昵称'),
        ...baseValidationRules.length(2, 20, '昵称长度在 2 到 20 个字符')
      ],
      email: [
        ...baseValidationRules.required('请输入邮箱'),
        ...baseValidationRules.email()
      ],
      phoneNumber: [
        ...baseValidationRules.required('请输入手机号'),
        ...baseValidationRules.phone()
      ],
      password: [
        ...baseValidationRules.required('请输入密码'),
        ...baseValidationRules.password(6, 20)
      ],
      status: [
        ...baseValidationRules.required('请选择状态')
      ]
    })
  },

  // 角色相关验证
  role: {
    form: (): FormRules => ({
      roleName: [
        ...baseValidationRules.required('请输入角色名称'),
        ...baseValidationRules.length(2, 20, '角色名称长度在 2 到 20 个字符')
      ],
      roleKey: [
        ...baseValidationRules.required('请输入权限字符'),
        ...baseValidationRules.alphanumeric('权限字符只能包含字母和数字')
      ],
      roleSort: [
        ...baseValidationRules.required('请输入显示顺序'),
        ...baseValidationRules.positiveInteger('显示顺序必须是正整数')
      ],
      dataScope: [
        ...baseValidationRules.required('请选择数据范围')
      ],
      status: [
        ...baseValidationRules.required('请选择状态')
      ]
    })
  },

  // 菜单相关验证
  menu: {
    form: (): FormRules => ({
      title: [
        ...baseValidationRules.required('请输入菜单名称'),
        ...baseValidationRules.length(2, 20, '菜单名称长度在 2 到 20 个字符')
      ],
      menuType: [
        ...baseValidationRules.required('请选择菜单类型')
      ],
      path: [
        ...baseValidationRules.required('请输入路由地址'),
        ...baseValidationRules.pattern(/^\/.*/, '路由地址必须以 / 开头')
      ],
      component: [
        ...baseValidationRules.required('请输入组件路径')
      ],
      sort: [
        ...baseValidationRules.required('请输入显示排序'),
        ...baseValidationRules.positiveInteger('显示排序必须是正整数')
      ],
      status: [
        ...baseValidationRules.required('请选择状态')
      ]
    })
  },

  // 部门相关验证
  dept: {
    form: (): FormRules => ({
      deptName: [
        ...baseValidationRules.required('请输入部门名称'),
        ...baseValidationRules.length(2, 20, '部门名称长度在 2 到 20 个字符')
      ],
      deptCode: [
        ...baseValidationRules.required('请输入部门编码'),
        ...baseValidationRules.alphanumeric('部门编码只能包含字母和数字')
      ],
      leader: [
        ...baseValidationRules.required('请输入负责人'),
        ...baseValidationRules.length(2, 10, '负责人姓名长度在 2 到 10 个字符')
      ],
      phone: [
        ...baseValidationRules.phone('请输入正确的手机号格式')
      ],
      email: [
        ...baseValidationRules.email('请输入正确的邮箱格式')
      ],
      sort: [
        ...baseValidationRules.required('请输入显示排序'),
        ...baseValidationRules.positiveInteger('显示排序必须是正整数')
      ],
      status: [
        ...baseValidationRules.required('请选择状态')
      ]
    })
  },

  // 系统设置相关验证
  settings: {
    form: (): FormRules => ({
      systemName: [
        ...baseValidationRules.required('请输入系统名称'),
        ...baseValidationRules.length(2, 20, '系统名称长度在 2 到 20 个字符')
      ],
      systemVersion: [
        ...baseValidationRules.required('请输入系统版本'),
        ...baseValidationRules.pattern(/^\d+\.\d+\.\d+$/, '版本号格式：x.y.z')
      ],
      systemDescription: [
        ...baseValidationRules.length(0, 100, '系统描述长度不能超过 100 个字符')
      ],
      copyright: [
        ...baseValidationRules.length(0, 50, '版权信息长度不能超过 50 个字符')
      ]
    })
  }
}

// 通用验证函数
export const validationUtils = {
  // 验证邮箱
  validateEmail: (email: string): boolean => {
    const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    return pattern.test(email)
  },

  // 验证手机号
  validatePhone: (phone: string): boolean => {
    const pattern = /^1[3-9]\d{9}$/
    return pattern.test(phone)
  },

  // 验证密码强度
  validatePasswordStrength: (password: string): { score: number; message: string } => {
    let score = 0
    const messages: string[] = []

    if (password.length >= 8) score += 1
    else messages.push('密码长度至少8位')

    if (/[a-z]/.test(password)) score += 1
    else messages.push('包含小写字母')

    if (/[A-Z]/.test(password)) score += 1
    else messages.push('包含大写字母')

    if (/\d/.test(password)) score += 1
    else messages.push('包含数字')

    if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) score += 1
    else messages.push('包含特殊字符')

    const strengthLevels = ['很弱', '弱', '一般', '强', '很强']
    const message = messages.length > 0 ? `建议：${messages.join('、')}` : `密码强度：${strengthLevels[score - 1]}`

    return { score, message }
  },

  // 验证身份证号
  validateIdCard: (idCard: string): boolean => {
    const pattern = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
    return pattern.test(idCard)
  },

  // 验证URL
  validateUrl: (url: string): boolean => {
    const pattern = /^https?:\/\/.+/
    return pattern.test(url)
  },

  // 验证IP地址
  validateIp: (ip: string): boolean => {
    const pattern = /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/
    return pattern.test(ip)
  },

  // 验证端口号
  validatePort: (port: string | number): boolean => {
    const portNum = typeof port === 'string' ? parseInt(port, 10) : port
    return portNum >= 1 && portNum <= 65535
  }
}

// 表单验证工具
export const formValidationUtils = {
  // 验证整个表单
  validateForm: async (formRef: any): Promise<boolean> => {
    try {
      await formRef.validate()
      return true
    } catch {
      return false
    }
  },

  // 重置表单验证
  resetFormValidation: (formRef: any) => {
    formRef?.clearValidate()
  },

  // 验证特定字段
  validateField: async (formRef: any, field: string): Promise<boolean> => {
    try {
      await formRef.validateField(field)
      return true
    } catch {
      return false
    }
  },

  // 获取表单错误信息
  getFormErrors: (formRef: any): Record<string, string> => {
    const errors: Record<string, string> = {}
    if (formRef?.fields) {
      Object.keys(formRef.fields).forEach(field => {
        const fieldErrors = formRef.fields[field].validateMessage
        if (fieldErrors) {
          errors[field] = fieldErrors
        }
      })
    }
    return errors
  }
}

// 导出所有验证规则
export default {
  baseValidationRules,
  businessValidationRules,
  validationUtils,
  formValidationUtils
}
